package com.duowei.diandan.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;

import com.duowei.diandan.R;
import com.duowei.diandan.db.entry.Gklx;

import java.util.List;

public class TableTypeAdapter extends RecyclerView.Adapter<TableTypeAdapter.ViewHolder> {

    private List<Gklx> mList;
    private int mChecked = -1;

    public TableTypeAdapter(List<Gklx> list) {
        mList = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.recycler_item_table_type, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Gklx gklx = mList.get(position);

        holder.mTextView.setText(gklx.getGklx());

        if (mChecked == holder.getAdapterPosition()) {
            holder.mTextView.setChecked(true);
        } else {
            holder.mTextView.setChecked(false);
        }

        holder.mTextView.setOnClickListener(v -> {
            if (holder.mTextView.isChecked()) {
                mChecked = -1;
            } else {
                mChecked = holder.getAdapterPosition();
            }

            notifyDataSetChanged();
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public Gklx getCheckedItem() {
        if (mChecked == -1) {
            return null;
        } else {
            return mList.get(mChecked);
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        CheckedTextView mTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            mTextView = (CheckedTextView) itemView;
        }
    }
}
